package ca.seia.comp6521.a1.externalmergesort;

import java.io.FileNotFoundException;
import java.io.IOException;

public class ExternalMergeSortExecutionController {
	
	private static final String SUBLIST_DIRECTORY = "c:\\comp6521_files\\phase1\\sublists\\";
	private static final String PHASEII_SUBLIST_DIRECTORY = "c:\\comp6521_files\\phase2\\sublists\\";
	private static final String FILE_TO_SORT = "c:\\comp6521_files\\phase1\\large.dat";
//	private static final String FILE_TO_SORT = "C:\\comp6521_files\\verysmall.dat";
	private static final int MEMORY_BUFFER_IN_MB = 5;
	public static final int UNUSED_NUMBER = Integer.MIN_VALUE;
	
	public PhaseIStatistics ExecutePhaseI() throws IOException 
	{
		//TODO Pass the filePath and SubListDirectory via Command Line arguments
		PhaseIExecutioner phaseIExecutioner = new PhaseIExecutioner(SUBLIST_DIRECTORY, FILE_TO_SORT, MEMORY_BUFFER_IN_MB);
		PhaseIStatistics phase1Statistics = phaseIExecutioner.executePhaseI();
		System.out.println(phase1Statistics);
		return phase1Statistics;
	}

	public PhaseIIStatistics ExecutePhaseII(PhaseIStatistics phase1Statistics) throws FileNotFoundException
	{
		PhaseIIStatistics phaseIIStatistics = new PhaseIIStatistics();
		PhaseIIPassController phaseIIpassController = new PhaseIIPassController(phase1Statistics,PHASEII_SUBLIST_DIRECTORY);
		PhaseIIPassResult phaseIIResult = null;
		PhaseIIPassResult previousPhaseIIResult = null;
		
		long startTime =  System.currentTimeMillis();
		do {
			if(phaseIIpassController.isFirstPhaseIIPass) {
				phaseIIResult = phaseIIpassController.executePhaseIIPass(null);
				phaseIIStatistics.getPhaseIIPassResults().add(phaseIIResult);
			} else {
				phaseIIResult = phaseIIpassController.executePhaseIIPass(previousPhaseIIResult);
				phaseIIStatistics.getPhaseIIPassResults().add(phaseIIResult);
			}
			previousPhaseIIResult = phaseIIResult;
			if (phaseIIResult.getSortedSubListFiles().size() == 1) {
				phaseIIResult.setFinalPass(true);
			}
			System.out.println(phaseIIResult);
		}  while (!phaseIIResult.isFinalPass());
				
		long executionTime = System.currentTimeMillis() - startTime;
		phaseIIStatistics.setExecutionTime(executionTime);
		return phaseIIStatistics;
	}
	
	
}
